<template>
    <div>
        <el-card shadow="always">
            <div slot="header">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item>首页</el-breadcrumb-item>
                    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <!-- card body -->
            <div class="f-search">
                <el-input placeholder="请输入内容" v-model="query" clearable @clear="clearSearch">
                    <template slot="append">
                        <i class="el-icon-search" @click="search"></i>
                    </template>
                </el-input>
            </div>
            <div class="f-btn">
                <el-button type="primary" size="default" @click="dialogVisible=true">增加</el-button>
            </div>
            <el-table :data="userList" border style="width: 100%">
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="role_name" label="角色名"></el-table-column>
                <el-table-column prop="mobile" label="手机号"></el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scope">
                        <el-switch
                            @change="changeStatus(scope.row.id,$event)"
                            v-model="scope.row.mg_state"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                        ></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="注册时间">
                    <template slot-scope="scope">{{scope.row.create_time|dataFormate }}</template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" content="修改" placement="top">
                            <el-button
                                @click="editUser(scope.row)"
                                type="success"
                                size="small"
                                icon="el-icon-s-tools"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top">
                            <el-button
                                type="danger"
                                size="small"
                                @click="delUser(scope.row.id)"
                                icon="el-icon-delete"
                            ></el-button>
                        </el-tooltip>
                        <el-button
                            type="warning"
                            size="small"
                            @click="editRight(scope.row)"
                            icon="el-icon-setting"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination
                background
                layout="sizes,prev,pager,next,jumper,->,total"
                :page-size="pagesize"
                :current-page="pagenum"
                :page-sizes="[1,2,3,4]"
                :total="total"
                @size-change="sizeChange"
                @current-change="pageChange"
            ></el-pagination>
        </el-card>

        <!-- 添加弹框 -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%">
            <el-form
                status-icon
                ref="ruleForm"
                class="demo-ruleForm"
                label-width="70px"
                :model="ruleForm"
                :rules="addrules"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input type="text" autocomplete="off" v-model="ruleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" autocomplete="off" v-model="ruleForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="ruleForm.mobile"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addUserSubmit">提交</el-button>
                    <el-button @click="addresetUser()">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 修改弹框 -->
        <el-dialog title="修改用户" :visible.sync="editdialogVisible" width="40%">
            <el-form
                status-icon
                ref="editruleForm"
                class="demo-ruleForm"
                label-width="70px"
                :model="editruleForm"
                :rules="editrules"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input type="text" autocomplete="off" v-model="editruleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editruleForm.mobile"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="editUserSubmit">提交</el-button>
                    <el-button @click="editresetUser()">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 修改权限弹框 -->
        <el-dialog title="修改用户" :visible.sync="rigthShow" width="40%">
            <p>当前用户:{{userinfo.username}}</p>
            <p>当前权限:{{userinfo.role_name}}</p>
            <p>
                选择权限：
                <el-select v-model="rid" placeholder="请选择">
                    <el-option
                        v-for="item in roleList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id"
                    ></el-option>
                </el-select>
            </p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rigthShow = false">取 消</el-button>
                <el-button type="primary" @click="rightSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        let checkEmail = (rule, value, callback) => {
            let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            if (reg.test(value)) callback();
            else callback(new Error("邮箱格式不正确"));
        };
        let checkMobile = (rule, value, callback) => {
            let reg = /^1[3456789]\d{9}$/;
            if (reg.test(value)) callback();
            else callback(new Error("手机号码格式不正确"));
        };
        return {
            query: "",
            pagenum: 1,
            pagesize: 1,
            userList: [],
            total: 0,
            // 选的权限
            rid: "",
            // 当前角色的列表
            roleList: [],
            // 修改权限的信息对象
            userinfo: {
                username: "",
                role_name: "",
            },
            // 修改权限是否弹出
            rigthShow: false,
            // 添加表单是否弹出
            dialogVisible: false,
            // 修改表单是否弹出
            editdialogVisible: false,
            // 添加表单的数据
            ruleForm: {
                username: "",
                password: "",
                email: "",
                mobile: "",
            },
            // 修改表单的数据
            editruleForm: {
                id: "",
                username: "",
                email: "",
                mobile: "",
            },
            // 校验规则
            // 添加规则
            addrules: {
                username: [
                    {
                        required: true,
                        message: "用户名不能为空",
                        trigger: "blur",
                    },
                    {
                        min: 3,
                        max: 10,
                        message: "用户名只能是3-10字符",
                        trigger: "blur",
                    },
                ],
                password: [
                    {
                        required: true,
                        message: "密码不能为空",
                        trigger: "blur",
                    },
                    {
                        min: 3,
                        max: 10,
                        message: "密码只能是3-10字符",
                        trigger: "blur",
                    },
                ],
                email: [{ validator: checkEmail, trigger: "blur" }],
                mobile: [{ validator: checkMobile, trigger: "blur" }],
            },
            // 修改规则
            editrules: {
                username: [
                    {
                        required: true,
                        message: "用户名不能为空",
                        trigger: "blur",
                    },
                    {
                        min: 3,
                        max: 10,
                        message: "用户名只能是3-10字符",
                        trigger: "blur",
                    },
                ],
                email: [{ validator: checkEmail, trigger: "blur" }],
                mobile: [{ validator: checkMobile, trigger: "blur" }],
            },
        };
    },
    methods: {
        // 修改用户状态
        async changeStatus(id, state) {
            let { data: res } = await this.$axios.put(
                `users/${id}/state/${state}`
            );
            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);
            this.$message.success("修改用户状态成功");
            this.getUserList();
        },
        // 获取当前角色的列表
        async getRoleList() {
            let { data: res } = await this.$axios.get("roles");
            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);
            this.roleList = res.data;
        },
        // 获取用户信息列表
        async getUserList() {
            let { data: res } = await this.$axios.get("users", {
                params: {
                    query: this.query,
                    pagenum: this.pagenum,
                    pagesize: this.pagesize,
                },
            });

            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);
            this.userList = res.data.users;
            this.total = res.data.total;
        },
        //清除搜索的处理函数
        clearSearch() {
            this.query = "";
            this.pagenum = 1;
            this.getUserList();
        },
        // 点击搜素的处理函数
        search() {
            this.pagenum = 1;
            this.getUserList();
        },
        // 修改每页的展示个数
        sizeChange(val) {
            this.pagesize = val;
            this.pagenum = 1;
            this.getUserList();
        },
        // 页码修改
        pageChange(val) {
            this.pagenum = val;
            this.getUserList();
        },
        //修改用户信息
        async editUser(val) {
            let { data: res } = await this.$axios.get("users/" + val.id);
            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);
            this.editruleForm = {
                ...res.data,
            };
            this.editdialogVisible = true;
            console.log(res);
        },
        // 删除用户信息
        async delUser(id) {
            try {
                await this.$confirm("您确定要删除吗", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                });
                let { data: res } = await this.$axios.delete(`users/${id}`);
                if (res.meta.status !== 200)
                    return this.$message.error(res.meta.msg);
                this.$message.success("删除成功");

                // 判断删除之后是否需要页码减一
                if (this.pagenum !== 1 && this.userList.length === 1)
                    this.pagenum--;
                this.getUserList();
            } catch (error) {
                this.$message.error("取消删除");
            }
        },
        // 添加用户提交
        addUserSubmit() {
            this.$refs.ruleForm.validate(async (valid) => {
                if (!valid) return;
                let { data: res } = await this.$axios.post(
                    "users",
                    this.ruleForm
                );
                if (res.meta.status !== 201)
                    return this.$message.error(res.meta.msg);
                this.$message.success("添加用户成功");
                this.addresetUser();
                this.pagenum = 1;
                this.getUserList();
            });
        },
        // 修改用户提交
        editUserSubmit() {
            this.$refs.editruleForm.validate(async (valid) => {
                if (!valid) return;
                let { data: res } = await this.$axios.put(
                    "users/" + this.editruleForm.id,
                    this.editruleForm
                );
                if (res.meta.status !== 200)
                    return this.$message.error(res.meta.msg);
                this.$message.success("修改用户成功");
                this.editresetUser();
                this.getUserList();
            });
        },
        // 添加重置用户
        addresetUser() {
            this.$refs.dialogVisible.resetFields();
            this.dialogVisible = false;
        },
        // 修改重置用户
        editresetUser() {
            this.$refs.editruleForm.resetFields();
            this.editdialogVisible = false;
        },
        //修改用户权限
        editRight(row) {
            this.rid = "";
            this.rigthShow = true;
            this.userinfo = { ...row };
            console.log(this.userinfo);
        },
        // 修改权限提交
        async rightSubmit() {
            let { data: res } = await this.$axios.put(
                "users/" + this.userinfo.id + "/role",
                {
                    rid: this.rid,
                }
            );
            if (res.meta.status !== 200)
                return this.$message.error(res.meta.msg);
            this.getUserList();
            this.rigthShow = false;
        },
    },
    created() {
        this.getUserList();
        this.getRoleList();
    },
};
</script>
<style lang="less">
.f-search {
    width: 300px;
    float: left;
}
.f-btn {
    float: right;
}
.el-table {
    margin: 50px 0;
}
</style>
